package com.hwadee.springboot_lx.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;


@Configuration
public class RedisConfig {

    @Bean
    public JedisPool jedisPool() {
        // 创建连接池配置
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();

        // 禁用 JMX 注册
        poolConfig.setJmxEnabled(false);

        JedisPool jedisPool = new JedisPool(poolConfig, "localhost", 6379);

        return jedisPool;
    }

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        // 创建 Jedis 连接工厂
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName("localhost");
        jedisConnectionFactory.setPort(6379);
        return jedisConnectionFactory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 使用 String 序列化器序列化 key
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        // 使用 Jackson2 序列化器序列化 value
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        return redisTemplate;
    }
}



